package com.shanling.shanlingcontroller.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.linkplay.lpvr.app.BaseCoreApplication;
import com.shanling.shanlingcontroller.R;
import com.shanling.shanlingcontroller.base.BaseAppManager;
import com.shanling.shanlingcontroller.bean.Constants;
import com.shanling.shanlingcontroller.bean.LoginBean;
import com.shanling.shanlingcontroller.bean.MybluetoothDevice;
import com.shanling.shanlingcontroller.persenter.WXEntryPersenter;
import com.shanling.shanlingcontroller.persenter.contract.WXEntryContract;
import com.shanling.shanlingcontroller.ui.activity.BleActivity;
import com.shanling.shanlingcontroller.ui.activity.LoginActivity;
import com.shanling.shanlingcontroller.ui.activity.MainActivity;
import com.shanling.shanlingcontroller.utils.PreferenceUtil;
import com.shanling.shanlingcontroller.utils.ToastUtils;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.litepal.LitePal;

import java.util.List;

public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler,WXEntryContract.View {


    /**
     * 微信登录相关
     */
    private IWXAPI api;
    private WXEntryPersenter wxEntryPersenter;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //通过WXAPIFactory工厂获取IWXApI的示例
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID_WX,true);
        //将应用的appid注册到微信
        api.registerApp(Constants.APP_ID_WX);
        if(wxEntryPersenter==null){
            wxEntryPersenter=new WXEntryPersenter();
        }
        wxEntryPersenter.attachView(this);
        BaseAppManager.getInstance().addActivity(this);

        //注意：
        //第三方开发者如果使用透明界面来实现WXEntryActivity，需要判断handleIntent的返回值，如果返回值为false，则说明入参不合法未被SDK处理，应finish当前透明界面，避免外部通过传递非法参数的Intent导致停留在透明界面，引起用户的疑惑
        try {
            boolean result =  api.handleIntent(getIntent(), this);
            if(!result){
                Log.e("weiyu","参数不合法，未被SDK处理，退出");
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        api.handleIntent(data,this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
        finish();
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        switch (baseResp.errCode){
            case BaseResp.ErrCode.ERR_OK:
                String code = ((SendAuth.Resp) baseResp).code;
                wxEntryPersenter.doLogin(code);
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
            case BaseResp.ErrCode.ERR_BAN:
                ToastUtils.showToast(this, R.string.Wechatlogin_failed);
                finish();
                break;

        }
    }

    @Override
    public void logingSuccess(LoginBean bean) {
        PreferenceUtil preferenceUtil=PreferenceUtil.getInstance(this);
        preferenceUtil.setSessionId(bean.getSessionId());
        preferenceUtil.setUserName(bean.getUserName());
        preferenceUtil.setPassword("");
        ToastUtils.showToast(this, R.string.login_success);
        BaseAppManager.getInstance().finishActivityclass(LoginActivity.class);
        List<MybluetoothDevice> mybluetoothDevices = LitePal.findAll(MybluetoothDevice.class);
        if(mybluetoothDevices.size()==0){
            toActivity(BleActivity.class);
        }else {
            toActivity(MainActivity.class);
        }
    }



    private void toActivity(Class clazz) {
        Intent intent = new Intent(this,clazz);
        startActivity(intent);
        finish();
    }

    @Override
    public void finish() {
        super.finish();
        BaseAppManager.getInstance().removeActivity(this);
    }

    @Override
    public void loginFaild(String msg) {
        ToastUtils.showToast(this, R.string.Wechatlogin_failed+msg);
        finish();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        wxEntryPersenter.detachView();
    }
}